package chapter4;

import java.sql.*;

public class RequestJDBC {
	public static void main(String[] args) {
		RequestJDBC obj = new RequestJDBC();
		int num = obj.getUserNum();
		System.out.println("the number is " + String.valueOf(num));
	}
	private int getUserNum() {
		Connection conn = null ;
		PreparedStatement ps = null;
		ResultSet rs = null ;
		int num=0;
		try {
//			Class.forName("com.mysql.jdbc.Driver");
//			String url = "jdbc:mysql://localhost:3306/spring";
			Class.forName("com.mysql.cj.jdbc.Driver");
			String url = "jdbc:mysql://localhost:3306/mytest?userSSL=true&serverTimezone=GMT";
			String name = "root";
			String passw = "123456";
			try {
				conn = DriverManager.getConnection(url,name,passw);
				String sql = "select count(*) from student";
				ps = conn.prepareStatement(sql);
				rs = ps.executeQuery();
				rs.next();
				System.out.println(rs.getInt(1));
				num=rs.getInt(1);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}finally {
			//关闭数据库连接资源
			try {
				if (rs != null && !rs.isClosed( ) ) {
				rs. close() ;
			}
			}catch (SQLException e ) {
				e.printStackTrace ( ) ;
			}
			try {
				if (ps != null && ! ps.isClosed ()) {
				ps.close() ;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if (conn != null && !conn.isClosed () ) {
				conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace() ;
			}
		}
		return num;
	}
}
